<template>
  <div style="width: 40%; margin: 5px auto" class="card">
    <el-form ref="formRef" :rules="data.rules" :model="data.user" label-width="60px" style="padding: 20px">
      <div style="margin-bottom: 10px; text-align: right">
        <el-button type="primary" @click="handleRechargeAmount">充值</el-button>
      </div>
      <div style="text-align: center; margin-bottom: 20px">
        <el-upload
          :action="baseUrl + '/files/upload'"
          :on-success="handleFileUpload"
          :show-file-list="false"
          class="avatar-uploader"
        >
          <img v-if="data.user.avatar" :src="data.user.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </div>
      <el-form-item prop="username" label="用户名">
        <el-input disabled v-model="data.user.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item prop="name" label="昵称">
        <el-input v-model="data.user.name" placeholder="请输入昵称"></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="电话">
        <el-input v-model="data.user.phone" placeholder="请输入电话"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="data.user.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item prop="account" label="余额">
        <div> {{ data.user.account || 0 }} 元</div>
      </el-form-item>
      <div style="text-align: center">
        <el-button type="primary" @click="handleUpdate">保 存</el-button>
      </div>
    </el-form>


    <el-dialog title="充值余额" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="rechargeRef" :model="data" :rules="accountRule.rules" label-width="70px" style="padding: 20px">
        <el-form-item prop="account" label="金额">
          <el-input-number :min="1" :precision="2" v-model="data.account" placeholder="请输入您要充值的金额"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="rechargeAmount">确 定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
  import {reactive, ref} from 'vue'
  import request from '@/utils/request.js'
  import { ElMessage } from 'element-plus'

  const baseUrl = import.meta.env.VITE_BASE_URL

  const validatePhone = (rule, value, callback) => {
    if (value && !/^1[3-9]\d{9}$/.test(value)) {
      callback(new Error('手机号格式不正确'));
    } else {
      callback();
    }
  };

  const validateEmail = (rule, value, callback) => {
    if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
      callback(new Error('邮箱格式不正确'));
    } else {
      callback();
    }
  };

  const formRef = ref();
  const rechargeRef = ref();

  const data = reactive({
    user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
    formVisible: false,
    account: 100.0,
    rules: {
      name: [{required: true, message: '昵称不能为空', trigger: ['blur', 'change']}],
      phone: [
          {required: true, message: '电话不能为空', trigger: ['blur', 'change']},
          {validator: validatePhone, trigger: ['blur', 'change']}
      ],
      email: [
          {required: true, message: '邮箱不能为空', trigger: ['blur', 'change']},
          {validator: validateEmail, trigger: ['blur', 'change']}
      ],
    }
  })

  const accountRule = reactive({
    rules: {
      account: [{ required: true, message: '金额不能为空', trigger: 'blur' }]
    }
  })

  const loadAccount = () => {
    request.get('/user/query?id=' + data.user.id).then(res => {
      if (res.code === '200') {
        // 1.修改Vue模型的user对象的余额
        data.user.account = res.data.account
        // 2.修改浏览器localStorage的余额
        localStorage.setItem('xm-user', JSON.stringify(data.user))
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
  loadAccount()

  const handleFileUpload = (res) => {
    data.user.avatar = res.data
  }

  const emit = defineEmits(['updateUser'])
  const handleUpdate = () => {
    formRef.value.validate(valid => {
      if (valid) {
        request.put('/user/update', {
          id: data.user.id,
          name: data.user.name,
          phone: data.user.phone,
          email:  data.user.email
        }).then(res => {
          if (res.code === '200') {
            ElMessage.success('成功更新个人资料')
            localStorage.setItem('xm-user', JSON.stringify(data.user))
            emit('updateUser')
          } else {
            ElMessage.error(res.msg)
          }
        })
      }
    })
  }

  const rechargeAmount = () => {
    rechargeRef.value.validate(valid => {
      if (valid) {
        request.put('/user/recharge/' + data.account).then(res => {
          if (res.code === '200') {
            ElMessage.success('充值成功')
            data.formVisible = false
            data.user.account += data.account
            localStorage.setItem('xm-user', JSON.stringify(data.user))
            emit('updateUser')
          } else {
            ElMessage.error(res.msg)
          }
        })
      }
    })
  }

  const handleRechargeAmount = () => {
    data.formVisible = true
    data.account = 100.0
  }

</script>

<style scoped>
.avatar-uploader {
  height: 120px;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>